package com.ciwong.epaper.modules.reciteWords.dbreciteword;


import android.text.TextUtils;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.common.db.DBCallBack;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.libs.utils.CWLog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public abstract class BaseDBManager {
    private WordDetailDao wordDetailDao;
    private String TAG = "BaseDBManager";
    private String NAME = "word_";
    public static String BOOK_ID = "";

    protected BaseDBManager() {
        wordDetailDao = new WordDetailDao();
    }

    /**
     * 获取数据库基本名称（最后在拼接bookid 或者versionid组成完整的表名）
     *
     * @return
     */
    private String getBaseTableName() {
        long userId = EApplication.getInstance().getUserInfoBase().getUserId();
        if (EApplication.BRAND_ID <= 0) {
            return null;
        }
        if (userId <= 0)
            return null;

        return NAME + EApplication.BRAND_ID + userId;
    }


    public boolean creatTable(String versionId) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId)) bookId = BOOK_ID + "";
        boolean flag = true;
        String baseTableName = getBaseTableName();
        if (baseTableName == null)
            flag = false;
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        try {
            wordDetailDao.creatTable(baseTableName + bookId);
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    public boolean dropTable(String versionId) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId)) bookId = BOOK_ID + "";
        String baseTableName = getBaseTableName();
        if (baseTableName == null)
            return false;
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        wordDetailDao.dropTable(baseTableName + bookId);
        return true;
    }

    /**
     * 判断表是否存在
     *
     * @param versionId
     * @return
     */
    public boolean checkTableIsExist(String versionId) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId)) bookId = BOOK_ID + "";
        String baseTableName = getBaseTableName();
        if (baseTableName == null)
            return false;
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        return wordDetailDao.checkTableIsExist(baseTableName + bookId);
    }

    /**
     * 判断表中是否有数据
     *
     * @param versionId
     * @return
     */
    public boolean checkTableHasData(String versionId) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId)) bookId = BOOK_ID + "";
        String baseTableName = getBaseTableName();
        if (baseTableName == null)
            return false;
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        int rowCount = wordDetailDao.getRowCount(baseTableName + bookId);
        return rowCount <= 0 ? false : true;
    }

    /**
     * 通过did 选出四个选项
     *
     * @param versionId
     * @param dId
     * @return
     */
    protected List<WordDetail> executeGetOptions(String versionId, String dId) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId)) bookId = BOOK_ID + "";
        List<WordDetail> options = new ArrayList<>();
        String baseTableName = getBaseTableName();
        if (baseTableName == null)//当数据库表 基本名不存在时，（也就是数据表找不到）不在向下执行 返回空集合
            return options;
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        String tableName = baseTableName + bookId;
        int limitNum = 4;
        Set<WordDetail> set = new HashSet<>();
        if (!wordDetailDao.checkTableIsExist(tableName))
            wordDetailDao.creatTable(tableName);
        int rowCount = wordDetailDao.getRowCount(tableName);
        Random random = new Random();
        List<WordDetail> wordDetailsDid = wordDetailDao.queryByDId(tableName, dId);
        if (wordDetailsDid.size() <= 0)//当给的did 数据库中不存在时 返回空集合
            return options;
        set.add(wordDetailsDid.get(0));

        do {
            if (rowCount <= limitNum) {
                List<WordDetail> wordDetails = wordDetailDao.queryAll(tableName);
                set.addAll(wordDetails);
                break;
            }
            int rId = random.nextInt(rowCount);
            List<WordDetail> wordDetails = wordDetailDao.queryById(tableName, rId + "");
            labe:
            if (wordDetails != null && wordDetails.size() > 0) {
                WordDetail queryWord = wordDetails.get(0);
                if (queryWord != null && !queryWord.getdId().equals(dId)) {
                    String qWId = queryWord.getwId();
                    String qDId = queryWord.getdId();
                    String qWord = queryWord.getWords();
                    for (WordDetail wordDetail : set) {//次循环是为了排除相同单词选项
                        String wIdSet = wordDetail.getwId();
                        String dIdSet = wordDetail.getdId();
                        String wordSet = wordDetail.getWords();
                        if (wIdSet.equals(qWId) || dIdSet.equals(qDId) || wordSet.equals(qWord)) {//当有相同单词wid时就继续外层循环，不存储这个随机数据
                            break labe;
                        }
                    }
                    set.add(wordDetails.get(0));
                }
            }
        } while (set.size() < limitNum);
        options.addAll(set);
        return options;
    }

    protected WordDetail executeGetByDId(String versionId, String dId) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId) || bookId.equals("null")) {
            bookId = BOOK_ID + "";
        }
        String baseTableName = getBaseTableName();
        if (baseTableName == null)
            return null;
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        String tableName = baseTableName + bookId;
        WordDetail wordDetail = null;
        if (!wordDetailDao.checkTableIsExist(tableName))
            wordDetailDao.creatTable(tableName);
        List<WordDetail> wordDetails = wordDetailDao.queryByDId(tableName, dId);
        if (wordDetails != null && wordDetails.size() > 0)
            wordDetail = wordDetails.get(0);
        return wordDetail;
    }

    protected boolean executeAddData(String versionId, List<WordDetail> wordDetails, DBCallBack dbCallBack) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId)) bookId = BOOK_ID + "";
        String baseTableName = getBaseTableName();
        if (baseTableName == null)
            return false;
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        String tableName = baseTableName + bookId;
        if (!wordDetailDao.checkTableIsExist(tableName))
            wordDetailDao.creatTable(tableName);
        try {
            for (int i = 0; i < wordDetails.size(); i++) {
                WordDetail wordDetail = wordDetails.get(i);
                boolean addResult = wordDetailDao.add(tableName,
                        wordDetail.getdId(),
                        wordDetail.getwId(),
                        wordDetail.getWords(),
                        wordDetail.getWordFile(),
                        wordDetail.getWordType(),
                        wordDetail.getSymbol(),
                        wordDetail.getSyllable(),
                        wordDetail.getPretations(),
                        wordDetail.getSentences(),
                        wordDetail.getSentFile(),
                        wordDetail.getWordPic(),
                        wordDetail.getColor());
                if (!addResult)
                    return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 当数据存在时就不添加
     *
     * @param versionId
     * @param wordDetails
     * @param dbCallBack
     * @return
     */
    protected boolean executeaddIfNoExistData(String versionId, List<WordDetail> wordDetails, DBCallBack dbCallBack) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId)) bookId = BOOK_ID + "";
        String baseTableName = getBaseTableName();
        if (baseTableName == null)
            return false;
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        String tableName = baseTableName + bookId;
        if (!wordDetailDao.checkTableIsExist(tableName)) {
            wordDetailDao.creatTable(tableName);
        }
        try {
            if (wordDetailDao.getDb() != null) {
                wordDetailDao.getDb().beginTransaction();
            }
            //使用HashSet去除wordDetails中存在的重复单词
            HashSet<String> hasWordSet = new HashSet<>();
            for (int i = 0; i < wordDetails.size(); i++) {
                WordDetail wordDetail = wordDetails.get(i);
                if (!hasWordSet.contains(wordDetail.getWords())) {
                    hasWordSet.add(wordDetail.getWords());
                    boolean addResult = wordDetailDao.addIfNoExist(tableName,
                            wordDetail.getdId(),
                            wordDetail.getwId(),
                            wordDetail.getWords(),
                            wordDetail.getWordFile(),
                            wordDetail.getWordType(),
                            wordDetail.getSymbol(),
                            wordDetail.getSyllable(),
                            wordDetail.getPretations(),
                            wordDetail.getSentences(),
                            wordDetail.getSentFile(),
                            wordDetail.getWordPic(),
                            wordDetail.getColor());
                    if (!addResult) {
                        return false;
                    }
                } else {
//                    CWLog.i(TAG, i + ":executeaddIfNoExistData:重复单词Word=" + wordDetail.getWords());
                }
            }
            if (wordDetailDao.getDb() != null)
                wordDetailDao.getDb().setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (wordDetailDao.getDb() != null)
                    wordDetailDao.getDb().endTransaction();
                System.out.println("事务提交");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    protected boolean executeDeleteAll(String versionId) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId)) bookId = BOOK_ID + "";
        String baseTableName = getBaseTableName();
        if (baseTableName == null)
            return false;
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        String tableName = baseTableName + bookId;
        if (!wordDetailDao.checkTableIsExist(tableName))
            wordDetailDao.creatTable(tableName);
        wordDetailDao.deleteAll(tableName);
        return true;
    }

    protected List<WordDetail> executeQueryAll(String versionId) {
        String bookId = versionId;
        if (TextUtils.isEmpty(bookId)) bookId = BOOK_ID + "";
        String baseTableName = getBaseTableName();
        if (baseTableName == null)
            return new ArrayList<>();
        if (wordDetailDao == null)
            wordDetailDao = new WordDetailDao();
        String tableName = baseTableName + bookId;
        if (!wordDetailDao.checkTableIsExist(tableName))
            wordDetailDao.creatTable(tableName);
        List<WordDetail> wordDetails = wordDetailDao.queryAll(tableName);
        return wordDetails;
    }
}
